package com.wjjun.base.widget.status

import android.content.Context
import android.util.AttributeSet
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import com.wjjun.base.ui.viewmodel.BaseWindowViewModel

/**
 * 展示不同状态界面的控件
 * author : wangjunjun
 * date   : 2022/6/20
 * desc   :
 */
class StatusListPagerView : FrameLayout {

    private val TAG: String = "StatusPagerView"

    private val statusViewModelMap = HashMap<Status, BaseWindowViewModel>()

    private var statusPagerAdapter: StatusPagerAdapter? = null

    /**
     * 当前状态
     */
    private var currentStatus = Status(-1)

    constructor(context: Context) : super(context) {
        initViews()
    }

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        initViews()
    }

    private fun initViews() {
        layoutParams = ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT
        )
        removeAllViews()
    }

    /**
     * 添加界面
     */
    fun setStatusView(status: Status, viewModel: BaseWindowViewModel) {
        statusViewModelMap[status] = viewModel
    }

    /**
     * 设置状态
     */
    fun setStatus(status: Status) {
        if (!statusViewModelMap.containsKey(status) || currentStatus == status) {
            return
        }
        val viewModel = statusViewModelMap[status]
        if (viewModel == null || viewModel.getLayoutId() == 0) {
            Log.e(TAG, "切换状态错误，未定义状态：$status")
            return
        }
        if (statusPagerAdapter != null) {
            val pager = statusPagerAdapter?.getView(this, status, viewModel)
            currentStatus = status
            removeAllViews()
            addView(pager)
        }
    }

    fun getStatusViewModel(status: Status): BaseWindowViewModel? {
        return statusViewModelMap[status]
    }

    public fun setAdapter(adapter: StatusPagerAdapter) {
        this.statusPagerAdapter = adapter
    }

    interface StatusPagerAdapter {
        fun getView(view: View, status: Status, viewModel: BaseWindowViewModel): View?
    }

}